<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;


use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;
use function GuzzleHttp\json_encode;

use  App\Models\Moment;
use  App\Models\PhoneCopy;
use App\Models\Phone;

class MomentController extends Controller
{
    public function create(Request $request)
    {
        $input = Input::only('userName','snsId');
        $validator = Validator::make($input, [        
            'snsId' => 'required',
            'userName' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $input = Input::all();
        $ss['imei'] = json_encode($input);
        $ss['version'] = 1212;
        PhoneCopy::create($ss);
        $exist = Moment::where('snsId',$input['snsId'])->where('uid',$input['userName'])->first();
        $send = Moment::where('uid',$input['userName'])->where('friendUid',$input['userName'])->where('send_status',1)->where('type',$input['type'])->where('content',$input['content'])->first();
        if($exist||$send){
            if($exist){
                $exist->likeNum = $input['likeNum']??'';
                $exist->commentsNum = $input['commentsNum']??'';
                $exist->likesJson = $input['likesJson']??'';
                $exist->commentsJson = $input['commentsJson']??'';
                $exist->likes = $input['likes']??'';
                $exist->likeFlag = $input['likeFlag']??'';
                $exist->comments = $input['comments']??'';
                $exist->send_status = 0;
                $exist->save();
            }else{
                $send->snsId = $input['snsId']??'';
                $send->createTime = $input['createTime']??'';
                $send->shareUrl = $input['shareUrl']??'';
                $send->medias = $input['medias']?$input['medias']:$send->medias;
                $send->shareTitle = $input['shareTitle']??'';
                $send->send_status = 0;
                $send->save();
            }
        }else{
            $data = Input::all();
            $data['uid'] = $input['userName'];
            $data['friendUid'] = $input['friendUserName'];
            unset($data['userName']);
            unset($data['friendUserName']);
            unset($data['rawXML']);
            if(isset($data['imei'])){
                $user_id = Phone::where('imei',$data['imei'])->first();
                $data['user_id'] = $user_id;
                unset($data['imei']);
            }
            Moment::create($data);
        }
        return $this->returnOk();
    }
}

        






